<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/24
 * Time: 17:14
 */

namespace App\Base;

use App\BaseExt\Pagination;
use App\BaseExt\PHPExcel;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SearchType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;

define("YYMMDDHHIISS","Y-m-d H:i:s");
define("YMDHIS","YmdHis");
define("YYMMDD","Y-m-d");
define("YMD","Ymd");



class BaseController extends Controller {


    public $YYMMDDHHIISS      = "Y-m-d H:i:s";
    public $YMDHIS            = "YmdHis";
    public $HHIISS            = "H:i:s";
    public $YYMMDD            = "Y-m-d";

    public function __construct()
    {
        $request = Request::createFromGlobals();
        $uri = $request->getRequestUri();
        $uri = str_replace("/app_dev.php","",$uri);
        $uri = str_replace("/app.php","",$uri);
        $fileData = file_get_contents("./tmp/uri.txt");
        $fileData = json_decode($fileData,true);
        if (!$fileData)
            $fileData = [];
        if (!in_array($uri,$fileData)){
            $fileData[] = $uri;
        }
        file_put_contents("./tmp/uri.txt",json_encode($fileData));
    }
    public function jumpToRoute($route)
    {
        header("location:".$this->generateUrl($route));exit;
    }
    public function jumpToURL($url)
    {
        header("location:$url");exit;
    }

    public function adminChkLogin()
    {
        $user = $this->getUser();
        is_object($user);
        if (is_object($user) && $uid = $user->getId()) {
            return $uid;
        } else {
            $this->jumpToRoute("AdminLogin");
        }
    }

    public function checkUserLogin()
    {
        $user = $this->getUser();
        is_object($user);
        if (is_object($user) && $uid = $user->getId()) {
            return $uid;
        } else {
            return false;
        }
    }

    /**
     * json 格式输出结果
     * @param $status
     * @param $info
     * @param array $data
     * @return Response
     */
        public function json_out ($status,$info,$data = array())
    {

        $data = array(
            "s"=> $status?$status:0,
            "i"  => $info?$info:"",
            "d"  => $data?$data:"",
        );
        return new Response(json_encode($data),200,array("content-type"=>"application/json"));
    }

    /**
     * js弹窗提示结果后跳转
     * @param $msg
     * @param $path
     * @return Response
     */
    public function js_out($msg,$path = "javascript:history.go(-1);")
    {

        if (!$path || $path == "javascript:history.go(-1);") {
            $path=false;
        }
        $data = array(
            "s"=> 1,
            "i"  => $msg,
            "d"  => $path,
        );
        return new Response(json_encode($data),200,array("content-type"=>"application/json"));
//        $data = array(
//            "url"   => $path,
//            "msg"   => $msg,
//        );
//        return $this->render("LazyCommon/message.html.twig",$data);

    }

    /**
     * js弹窗提示结果后跳转
     * @param $msg
     * @param $path
     * @return Response
     */
    public function msg_out($msg,$path = "")
    {
        $data = array(
            "url"   => $path,
            "msg"   => $msg,
        );
        return $this->render("LazyCommon/msg.html.twig",$data);
    }

    /**
     * js弹窗提示结果后跳转
     * @param $msg
     * @param $path
     * @return Response
     */
    public function js_out_close($msg,$path = "javascript:window.close();")
    {
        $data = array(
            "url"   => $path,
            "msg"   => $msg,
        );
        return $this->render("LazyCommon/message.html.twig",$data);
    }

    /**
     * 获取必填参数
     * @param $paramName
     * @return bool|mixed
     */
    public function getParamRequired($paramName)
    {
        $request = Request::createFromGlobals();
        if ($request->request->has("$paramName")) {
            return $request->get("$paramName");
        }
        if ($request->query->has("$paramName")) {
            return $request->get("$paramName");
        }
        return false;
    }

    /**
     * @param $base_url
     * @param $total_rows
     * @param int $per_page
     * @return array
     */
    public function creatPage($base_url,$total_rows,$per_page = 10)
    {
        $config['first_url'] = $base_url;
        $config['base_url'] = $base_url;
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $per_page;
//        $config['reuse_query_string'] = TRUE;
//        $config["query_string_segment"] = "page";

        //分页基础配置
        $config['num_links'] = 3;
        $config['first_link'] = '首页';
        $config['prev_link'] = '«上一页';
        $config['cur_tag_open'] = '<span class="current">';
        $config['cur_tag_close'] = '</span>';
        $config['next_link'] = '下一页»';
        $config['last_link'] = '末页';

        $pageBuilder = new Pagination($config);
        $page =  $pageBuilder->create_links();
        return array(
            "total"     => $total_rows,
            "perPage"   => $per_page,
            "page"      => $page
        );
    }


    public function createMyForm($FBNameSpace , $entity , $actionUrl = "" , $method = "POST")
    {
        $config = array(
            "entity"   => $entity,
            "actionUrl"   => $actionUrl,

        );
        $options = array(
            "attr"  => array(
                "action" => $actionUrl,
                "method" => $method,
            ),
        );

        $form = $this->createFormBuilder($config["entity"],$options)->getForm();
//        $m = $this->getDoctrine()->getManager();
        $m = $this->getDoctrine();
        $formRows = new $FBNameSpace($m);
        foreach ($formRows->formConfig() as $key => $param) {
            $form->add(
                $key,
                $this->type2RealType($param["showType"]),
                $this->basicParam($param["showType"],$param["label"],$param["dataType"],$param["option"],isset($param["class"])?$param["class"]:"")
            );
        }
        return $form;
    }

    private function type2RealType($type)
    {
        switch ($type) {
            case "article":
                $realType = "textarea";
                $realType = TextareaType::class;
                break;
            case "select":
                $realType = "choice";
                $realType = ChoiceType::class;
                break;
            case "radio":
                $realType = "choice";
                $realType = ChoiceType::class;
                break;
            case "checkbox":
                $realType = "choice";
                $realType = ChoiceType::class;
                break;
            case "pic":
                $realType = "search";
                $realType = SearchType::class;

                break;
            case "pics":
                $realType = "search";
                $realType = SearchType::class;
                break;
            case "datetime":
            case "time":
            case "date":
                $realType = "text";
                $realType = TextType::class;
                break;
            default:
                $realType = $type;
                $realType = TextType::class;

        }
        return $realType;
    }

    public function basicParam($type,$name,$dataType,$option,$class = "")
    {
        $attr = isset($option["attr"])?$option["attr"]:array();
        $attr = array_merge($attr,array("datatype"=>$dataType));
        $otherParam = isset($option["other"])?array_merge(array("label"=>$name),$option["other"]):array("label"=>$name);
        switch ($type) {
            case "text"://选择
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "layui-input $class",
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
                break;
            case "textarea"://选择
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "layui-textarea $class",
                    ),$attr),
                ),$otherParam);
                return $basic;
                break;
            case "select"://选择
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-single-select $class",
                    ),$attr),
                    "expanded"=>"0",
                    "multiple"=>"0",
                ),$otherParam);
                return $basic;
                break;
            case "radio"://单选
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "rule-multi-radio  $class",
                        "lay-skin" => "primary",
                    ),$attr),
                    "expanded"=>"1",
                    "multiple"=>"0",
                ),$otherParam);
                return $basic;
                break;
            case "checkbox"://多选
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "lay-skin" => "primary",
                        "class" => "rule-multi-checkbox  $class",
                    ),$attr),
                    "expanded"=>"1",
                    "multiple"=>"1",
                ),$otherParam);
                return $basic;
                break;
            case "article"://富文本
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class" => "UEditor",
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
                break;
            case "date"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"layui-input layui-my-date  $class" ,
//                        'onfocus'=>"WdatePicker({dateFmt:'yyyy-MM-dd'})" ,
//                        'datatype'=>"/^\s*$|^\d{4}\-\d{1,2}\-\d{1,2}$/" ,
//                        'errormsg'=>"请选择正确的日期",
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
                break;
            case "time"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"layui-input layui-my-time layui-inline  $class" ,
//                        'onfocus'=>"WdatePicker({dateFmt:'HH:mm:ss'})" ,
//                        'datatype'=>"/^(\d{1,2}:){2}\d{1,2}$/" ,
//                        'errormsg'=>"请选择正确的日期",
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
                break;
            case "datetime"://时间
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        "class"=>"layui-input layui-my-date-time layui-inline  $class" ,
//                        'onfocus'=>"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" ,
//                        'datatype'=>"/^\s*$|^\d{4}\-\d{1,2}\-\d{1,2}\s{1}(\d{1,2}:){2}\d{1,2}$/" ,
//                        'errormsg'=>"请选择正确的日期",
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
                break;
            default:
                $basic = array_merge(array(
                    "attr"  => array_merge(array(
                        //nothing
                    ),$attr),
                    "required"  => False
                ),$otherParam);
                return $basic;
        }
    }
    /*项目通用化增删改查*/
    public $entitySetting ;

    public function setSetting($entitySetting)
    {
        $this->entitySetting = $entitySetting;
    }

    public function comAdd( $entity = null)
    {
        if (!$entity) {
            $entity = new $this->entitySetting->entityPath();
        }
        $form = $this->createMyForm($this->entitySetting->SettingPath, $entity,   $this->generateUrl($this->entitySetting->entityName."DoAdd"));

        $show = $form->createView();

        $entityCnName = $this->entitySetting->entityCnName;
        $data = array(
            "title" => "新增$entityCnName",
            "submitUrl" => $this->generateUrl($this->entitySetting->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
//        return $this->render($this->entitySetting->bundleName."/".$this->entitySetting->entityName."/add.php.twig",$data);
        return $this->render("Base/common.add.html.twig",$data);
    }

    public function comDoAdd($request , $entity = null)
    {
        if (!$entity) {
            $entity = new $this->entitySetting->entityPath();
        }
        $form = $this->createMyForm($this->entitySetting->SettingPath,  $entity);
        $form->handleRequest($request);
//        var_dump($form->isSubmitted());
//        var_dump($form->isValid());
//        if ($form->isSubmitted() && $form->isValid()) {
        if ($form->isSubmitted()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
//            return $this->redirectToRoute($this->entitySetting->entityName.'Lists');
            return $this->js_out("保存成功",$this->generateUrl($this->entitySetting->entityName."Lists"));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl($this->entitySetting->entityName."PreAdd"));
        }
    }

    public function comEdit($entity)
    {
        $action = $this->generateUrl($this->entitySetting->entityName."DoEdit",array("id"=>$entity->getId()));
        $form = $this->createMyForm($this->entitySetting->SettingPath,  $entity ,  $action );
        $show = $form->createView();
        $entityCnName = $this->entitySetting->entityCnName;
        $data = array(
            "title" => "管理$entityCnName",
            "submitUrl" => $this->generateUrl($this->entitySetting->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
//        return $this->render($this->entitySetting->bundleName."/".$this->entitySetting->entityName."/add.php.twig",$data);
        return $this->render("Base/common.add.html.twig",$data);
    }

    public function comDoEdit(Request $request, $entity)
    {
        $form = $this->createMyForm($this->entitySetting->SettingPath,  $entity );
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
//            return $this->redirectToRoute($this->entitySetting->entityName.'Lists');
            return $this->js_out("保存成功",$this->generateUrl($this->entitySetting->entityName."Lists"));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl($this->entitySetting->entityName."PreEdit",array("id"=>$entity->getId())));
        }
    }

    public function comLists($tools)
    {
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $lists = $this->getLists($page,$per_page);
        $total = $lists["total"];

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl($this->entitySetting->entityName."Tools"),
            "addUrl"=>$this->generateUrl($this->entitySetting->entityName."PreAdd"),
        );


        $entityCnName = $this->entitySetting->entityCnName;
        return $this->render($this->entitySetting->bundleName."/".$this->entitySetting->entityName."/list.php.twig", array(
            'title'     => "$entityCnName 列表",
            "tools"   => $tools,
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl($this->entitySetting->entityName."Lists"),$total,$per_page),
        ));
    }



    public function comCatLists()
    {
        $lists = $this->getLists(0,0);
        $table = str_replace("_","",$this->entitySetting->table);
//        $table = $this->entitySetting->entity;
        $data = $this->buildeCatTree($lists["data"],$table);
        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl($this->entitySetting->entityName."Tools"),
            "addUrl"=>$this->generateUrl($this->entitySetting->entityName."PreAdd"),
        );
        $rep = $this->getDoctrine()->getManager()->getRepository($this->entitySetting->bundleName.":".$this->entitySetting->entityName);
        $classes = $rep->findAll();

        $entityCnName = $this->entitySetting->entityCnName;
        return $this->render($this->entitySetting->bundleName."/".$this->entitySetting->entityName."/cat_list.php.twig", array(
            'title'     => "$entityCnName 列表",
            "classes"   => $classes,
            'urls'      => $urls,
            'lists'     => $data,
        ));
    }

    public function buildeCatTree($data,$table = "")
    {
        if ($table) {
            $table = $table."_";
        }
        $newData = array();
        foreach ($data as $d) {//根据parent取出子项
            $newData[$d[$table."id"]] = $d;
        }
        $groupByParent = array();
        foreach ($newData as $d) {//根据parent取出子项
            $groupByParent[$d[$table."parent"]][$d[$table."orders"]*1000000 + $d[$table."id"]] = $d;
        }

        $curParent = 0;
        $isEnd = 0;
        $sortedArray = array();
        $i = 0;
        if (isset($groupByParent[$curParent])) {
            do {
                ksort($groupByParent[$curParent]);
                if (isset($groupByParent[$curParent])) {//此ID下有分类
                    //设置这个父元素的相邻父元素
                    $first = reset($groupByParent[$curParent]);
                    //取出当前分组的第一个元素并删除
                    $sortedArray[] = $first;
                    array_shift($groupByParent[$curParent]);
                    if (isset($groupByParent[$first[$table."id"]])) {//查找子元素
                        $curParent = $first[$table."id"];
                    }else{//子元素没有的时候需要检测时候还有兄弟元素
                        while(empty($groupByParent[$curParent])) {
                            unset($groupByParent[$curParent]);
                            if ($curParent == 0) {
                                $isEnd = 1;
                                break;
                            }
                            $curParent = $newData[$curParent][$table."parent"];
                        }
                    }
                    if ($isEnd) {break;}
                }
                $i ++ ;
            } while (count($sortedArray) < count($newData) && $i < 100);
        } else {
            $sortedArray = $newData;
        }
        return $sortedArray;
    }

    public function getLists($page,$per_page)
    {
        $modelPath = $this->entitySetting->modelPath;

        $model = new $modelPath($this->getDoctrine());
        $params = array();

        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
//        $params["orderBy"][$table]["orders"]="DESC";
        $params["groupBy"][$table]=array("id");
        $rst = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);
        return $rst;
    }

    public function comTools(Request $request)
    {
        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out("参数丢失",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out("参数丢失",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$id);
                    $em->remove($entity);
                }
                $em->flush();
            }
        }
        //如果是修改操作执行修改操作
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$data["id"]);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    if ( !in_array( $key , $this->entitySetting->editKeys ) ) { continue; }
                    $func = "set$key";
                    $entity->$func($val);
                }
                $em->persist($entity);
                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        return $this->redirect($this->generateUrl($this->entitySetting->entityName."Lists")."?".$queryStr);
    }


    public function updateUserSession($userInfo)
    {
        $userSession = array(
            "uid"       => $userInfo["id"],
            "groups"    => $userInfo["groups"],
            "level"     => $userInfo["level"],
            "account"   => $userInfo["account"],
        );
        $session = $this->container->get("session");
        foreach ($userSession as $key => $val) {
            $session->set($key,$val);
        }
    }

    public function log_out($info)
    {
        $logger = $this->get("logger");
        $logger->info(json_encode($info));
    }


    /**
     * @param $entity
     * @return array
     */
    public function toArray(&$entity)
    {
        if(!$entity) return[];
        $methods = (get_class_methods(get_class($entity)));
        $arrData = array();
        foreach ($methods as $method) {
            $attr = lcfirst(substr($method,3));
            $funcName = "get".ucfirst($attr);
            $arrData[$attr] = $entity->$funcName();
        }
        $entity = $arrData;
        return $arrData;
    }



    /**
     * @return Session
     */
    public function mySession()
    {
        return $this->get("session");
    }



    /**
     * @return EntityManager
     */
    public function myEm()
    {
        return $this->getDoctrine()->getManager();
    }

    public function myRep($name)
    {
        return $this->getDoctrine()->getRepository($name);
    }


    public function setSessionData($array)
    {
        $session = $this->mySession();
        foreach ($array as $k=>$v) {
            $session->set("$k",$v);
        }
    }
    public function getSessionData($key)
    {

        $session = $this->mySession();
        return $session->get($key);
    }



    /*********************验证码相关************************/
    //获取图片验证码
    /**
     * @param $headPics
     * @return array
     */
    public function createImgFromHead($headPics)
    {
        $code = "";
        $url = array();
        foreach ($headPics as $key => $headPic) {
            $rnd = rand(0,3);
            $source = imagecreatefrompng(".".$headPic);
            $rotate = imagerotate($source, 90*$rnd, 0);
            //旋转后的图片保存
            //创建临时目录
            if (!is_dir("./tmp/headCaptcha/".date("Ymd"))) {
                mkdir("./tmp/headCaptcha/".date("Ymd"));
            }
            $savePath = "/tmp/headCaptcha/".date("Ymd")."/".uniqid().rand(111111,999999).".png";
            imagepng($rotate,".".$savePath);
            $code.= $rnd;
            $url[] = $savePath;
        }
        return array(
            "code"   => $code,
            "urls"  => $url
        );
    }

    public function checkHeadCaptchaCode($code)
    {

        $cap = $this->getSessionData("headCaptcha");
        return $cap == $code;
    }

    public function usePic($path,$toPath){

        $this->log_out("=====4======");
        $this->log_out($path);
        $this->log_out($toPath);
        $this->log_out(!file_exists(".".$path));
        $this->log_out(file_exists(".".$path) && (strpos($path,BaseConfig::__USER_PIC_TMP__) !== false));
        if (file_exists(".".$path) && (strpos($path,BaseConfig::__USER_PIC_TMP__) !== false)) {
            $picName = basename($path);
            if (!file_exists(".".$toPath)) {
//                mkdir($toPath);
                mkdir(".".$toPath,0777,true);
            }
            $targetPath = $toPath."/".$picName;
            copy(".".$path,".".$targetPath);
            unlink(".".$path);
            return $targetPath;
        }else if(!file_exists(".".$path)){
            return "";
        } else {
            return $path;
        }
    }

    public function usePicArray($pathArray,$toPath){
        $newData = array();
        foreach ($pathArray as $key=>$onePic) {
            if ($onePic = $this->usePic($onePic,$toPath)) {
                $newData[] = $onePic;
            }
        }
        return $newData;
    }

    public function dropPic($path,$userId){

        $this->log_out("=====3======");
        $this->log_out(!file_exists(".".$path));
        if(!file_exists(".".$path)){
            return false;
        }
        if (!(strpos($path,BaseConfig::__USER_FILE_SHOP__."$userId/") === false)) {
            unlink(".".$path);
        }else if (!(strpos($path,BaseConfig::__USER_FILE_USER__."$userId/") === false)) {
            unlink(".".$path);
        } else if (!(strpos($path,BaseConfig::__USER_PIC_TMP__) === false)) {
            unlink(".".$path);
        } else {
            $this->log_out("危险的删除行为：userid=>".$userId.";path=>".$path);
        }
    }

    public function dropPicOne($oldData,$newData,$userId){
        $this->log_out("======1=====");
        $this->log_out($oldData);
        $this->log_out($newData);
        if ($oldData != $newData) {
            $this->log_out("=====2======");
            $this->log_out($oldData);
            $this->log_out($newData);
            $this->dropPic($oldData,$userId);
        }
    }
    public function dropPicArray($oldData,$newData,$userId){
        $delArray = array_diff($oldData,$newData);
        foreach ($delArray as $pic) {
            $this->dropPic($pic,$userId);
        }
    }


    public function getWeek($time)
    {
        $weekArray=array("日","一","二","三","四","五","六");
        return $weekArray[date("w",$time)];
    }



    /**
     * 计算两组经纬度坐标 之间的距离;params ：lat1 ； lng1 经度1； lat2 纬度2； lng2 经度2；
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return float
     */
    function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $EARTH_RADIUS = 6378.137;
        $PI = 3.1415926;
        $decimal = 2;// decimal小数点后几位
        $len_type = 2;// len_type长度单位 （1:m or 2:km);
        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $s = $s * $EARTH_RADIUS;
        $s = round($s * 1000);
        if ($len_type > 1)
        {
            $s /= 1000;
        }
        return round($s, $decimal);
    }

    public function fillEntityFromRequest(&$entity)
    {
        $orgData = $entity;
        $params = $this->toArray($orgData);
        foreach ($params as $key=>$value) {
            if ($key == "id") {
                continue;
            }
            if (!$$key = $this->getParamRequired("$key") ) {
                if($$key === false){
                    continue;
                }
            }
            $func = "set".ucfirst($key);
            $entity->$func($$key);
        }
        return $entity;
    }

    /**
     * @param array $old
     * @param array $new
     * @param string $prefix
     * @return mixed
     */
    public function concat($old,$new,$prefix = ""){
        foreach ($new as $key => $value) {
            $old[$prefix.ucfirst($key)] = $value;
        }
        return $old;
    }






    /**
     * @param string $timeOrDate
     * @return int
     */
    public function getWeekStart($timeOrDate = "")
    {
        if (!$timeOrDate) {
            $timeOrDate = time();
        }
        if (is_string($timeOrDate)) {
            $time = strtotime($timeOrDate);
        } else {
            $time = (int) $timeOrDate;
        }
        return $time - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600;
    }

    /**
     * @param string $timeOrDate
     * @return int
     */
    public function getWeekEnd($timeOrDate = "")
    {
        if (!$timeOrDate) {
            $timeOrDate = time();
        }
        if (is_string($timeOrDate)) {
            $time = strtotime($timeOrDate);
        } else {
            $time = (int) $timeOrDate;
        }
        return $time + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600;
    }


    /**
     * @param string $timeOrDate
     * @return int
     */
    public function getDayStart($timeOrDate = "")
    {
        if (!$timeOrDate) {
            $timeOrDate = time();
        }
        if (is_string($timeOrDate)) {
            $time = strtotime($timeOrDate);
        } else {
            $time = (int) $timeOrDate;
        }
        return strtotime(date( "Y-m-d" , $time ));
    }

    /**
     * @param string $timeOrDate
     * @return int
     */
    public function getDayEnd($timeOrDate = "")
    {
        if (!$timeOrDate) {
            $timeOrDate = time();
        }
        if (is_string($timeOrDate)) {
            $time = strtotime($timeOrDate);
        } else {
            $time = (int) $timeOrDate;
        }
        return strtotime(date( "Y-m-d" , $time )) + 24 * 3600 - 1;
    }



    /**
     * @param string $timeOrDate
     * @return int
     */
    public function getMonthStart($timeOrDate = "")
    {
        if (!$timeOrDate) {
            $timeOrDate = time();
        }
        if (is_string($timeOrDate)) {
            $time = strtotime($timeOrDate);
        } else {
            $time = (int) $timeOrDate;
        }
        return strtotime(date('Y-m', $time) . '-01 00:00:00');
    }

    /**
     * @param string $timeOrDate
     * @return int
     */
    public function getMonthEnd($timeOrDate = "")
    {
        if (!$timeOrDate) {
            $timeOrDate = time();
        }
        if (is_string($timeOrDate)) {
            $time = strtotime($timeOrDate);
        } else {
            $time = (int) $timeOrDate;
        }
        return strtotime(date('Y-m', $time) . '-' . date('t', time()) . ' 23:59:59');
    }


    public function timeToYMDHIS($time = 0,$pos = "",$isEnd = 0)
    {
        if (!$pos) {
            if (!$time) {
                $time = time();
            }
            return date("Y-m-d H:i:s",$time);
        }
        $isEnd = 1;
        if ($isEnd) {
            switch ($pos) {
                case "Y":
                    $day = $time / (3600 * 24 * 365);
                    return floor($day);
                case "m":
                    $day = $time / (3600 * 24 * 30);
                    return floor($day);
                case "d":
                    $day = $time / (3600 * 24);
                    return floor($day);
                case "H":
                    $day = $time / (3600);
                    return floor($day);
                case "i":
                    $day = $time / (60);
                    return floor($day);
            }
        }else{
            return (int)date("$pos",$time);
        }

    }

    public function timeToWords($time,$min = "i")
    {
        $str = "";
        $isEnd = 0;
        if ($num = $this->timeToYMDHIS( $time , "Y"  ,$isEnd) - 1970) {
            $str = $str . $num."年";
            $isEnd = 0;
        }else{
            $isEnd = 1;
        }
        if ($min == "Y") {return $str;}
        if ($num = $this->timeToYMDHIS( $time , "m"  ,$isEnd)) {
            $str = $str . $num."月";
            $isEnd = 0;
        }else{
            $isEnd = 1;
        }
        if ($min == "m") {return $str;}
        if ($num = $this->timeToYMDHIS( $time , "d"  ,$isEnd)) {
            $str = $str . $num."天";
            $isEnd = 0;
        }else{
            $isEnd = 1;
        }
        if ($min == "d") {return $str;}
        if ($num = $this->timeToYMDHIS( $time , "H"  ,$isEnd)) {
            $str = $str . $num."小时";
            $isEnd = 0;
        }else{
            $isEnd = 1;
        }
        if ($min == "H") {return $str;}
        if ($num = $this->timeToYMDHIS( $time , "i"  ,$isEnd)) {
            $str = $str . $num."分钟";
            $isEnd = 0;
        }else{
            $isEnd = 1;
        }
        if ($min == "i") {return $str;}
        if ($num = $this->timeToYMDHIS( $time , "s"  ,$isEnd)) {
            $str = $str . $num."秒";
            $isEnd = 0;
        }else{
            $isEnd = 1;
        }
        return $str;
    }





    public function dealWithImgInHtml($content)
    {

        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img src="'.BaseConfig::__BASE_URL__.'${1}" style="max-width:100%">', $content);
        return $content;
    }
    /**
     * @param $code
     * @param $time
     * @param $string
     * @return bool
     */
    public function checkVICode($code,$time,$string)
    {//string 生成：$phone + md5(md5($password))
        if (strtolower($code) == strtolower(md5($string.$time.BaseConfig::__VI__.$time.$string))) {
            return true;
        } else {
            return false;
        }
    }


    public function dealWithPhoneNumber($phone)
    {
        $start = substr($phone,0,3);
        $end = substr($phone,-4);
        return $start."****".$end;

    }

    /**
     * @param string $time
     * @return \DateTime
     */
    public function getDateTime($time = "")
    {
        if (!$time && $time !== 0) {
            $time = time();
        }
        $DateTime = new \DateTime();
        $DateTime->format("Y-m-d H:i:s");
        $DateTime->setTimestamp($time);
        return $DateTime;
    }


    public function createOrderSn($uid = "")
    {
        return date($this->YMDHIS).rand(1000,9999).$uid;
    }

    public function createPayCalBackCode($uid,$type="wx")
    {
        return md5($type.uniqid($uid).BaseConfig::__VI__.rand(1000,9999));
    }


    public function myExplodeNumbers($string)
    {
        preg_match_all("/[0-9\.?]+/",$string,$array);
        return $array[0];
    }


    public function excelOut($title,$arrayData,$fileName,$indexArray = [])
    {
        require_once (__DIR__."/../BaseExt/PHPExcel.php");
        $excel = new \PHPExcel();
        $excelHelper = new \ExcelAssistant();
        $titleLetter = $excelHelper->GetExcelTit(count($title));
//        var_dump($titleLetter);
        //设置标题
        $i = 0;
        foreach ($title as $key => $name) {
            if ( $indexArray ) {
                if (!in_array($i,$indexArray)) {
                    continue;
                }
            }
            $excel->getActiveSheet()->setCellValue($titleLetter[$key]."1",$name);
        }

        //设置内容
        foreach ($arrayData as $key => $row) {
            $i = 0;
            foreach ($row as $k => $v) {
                if (!is_string($v)) {
                    $v = json_encode($v);
                }
                $excel->getActiveSheet()->setCellValue($titleLetter[$i].($key + 2),$v);
                $i++;
            }
        }

//        直接输出到浏览器
        $objWriter = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$fileName.'.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }


    public function excelRead($path)
    {
        require_once (__DIR__."/../BaseExt/PHPExcel.php");
//        $excel = new \PHPExcel();
        $path = ".".$path;

        /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($path)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($path)){
                echo 'no Excel';
                return ;
            }
        }
        $re = array();
        $PHPExcel = $PHPReader->load($path);
        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet(0);
        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();
        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
        /**从第二行开始输出，因为excel表中第一行为列名*/
        for($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
            /**从第A列开始输出*/
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();/**ord()将字符转为十进制数*/
                $re[$currentRow - 2][] = $val;
            }
        }
        return $re;
    }


    public function js_login()
    {
        header('content-type:application/json;charset=utf8');
        $s = 203;
        $i = "请认证身份";
        $d = "";
        $re = array(
            "s"    => $s,
            "i"    => $i,
            "d"    => $d,
        );
        die(json_encode($re));
    }

}
